import styles from './Search.module.scss'

import { getGroupList } from '@renderer/ajax/api/common'
import { getDate } from '@renderer/utils/utils'
import { defineComponent, ref, reactive, watch, onMounted } from 'vue'

import { ElInput, ElDatePicker, ElSelect, ElOption, ElMessage } from 'element-plus'
import { useExpose } from '@renderer/utils'

import Radio from '@renderer/components/radio'

export default defineComponent({
  name: 'Search',
  emit: ['submit'],
  setup(props, { emit, slots }) {
    const state = reactive({
      btnType: 0,
      btnTime: 1,
      btnTypeList: ['自动加好友', '加群好友', '无限群发', '发布群公告', '群发监控'],
      // btnTypeList: ['自动加好友', '加群好友', '无限群发',],
      btnTimeList: ['今日', '本周', '本月', '自定义时间'],
      groupList: [],
      date: []
    })
    const form = reactive<any>({
      StartDate: null,
      EndDate: null,
      TaskKeyword: '',
      Groupchats: [] // 群列表
    })
    const onSearch = () => {
      const result = {}
      Object.keys(form).forEach((key) => {
        if (![null, NaN, undefined, ''].includes(form[key])) result[key] = form[key]
      })
      emit('submit', state.btnType, result)
    }
    const onChanegDate = (v: any) => {
      if (v) {
        form.StartDate = v[0]
        form.EndDate = v[1]
        onSearch()
      } else {
        onTime(1)
      }
    }
    const onType = (v: number) => {
      if (v != undefined) {
        state.btnType = v
        onSearch()
      }
    }
    const onTime = (v: number) => {
      state.btnTime = v
      let day = [getDate('dayStartOf'), getDate('dayEndOf')] // 今天
      let week = [getDate('weekStartOf'), getDate('dayEndOf')] // 本周
      let month = [getDate('monthStartOf'), getDate('dayEndOf')] // 本月

      switch (v) {
        case 0:
          onChanegDate(day)
          break
        case 1:
          onChanegDate(week)
          break
        case 2:
          onChanegDate(month)
          break
        case 3:
          if (state.date?.length) {
            onChanegDate(state.date)
          }
          break
      }
    }
    const onGroup = async () => {
      if (!state.groupList.length) {
        const res: any = await getGroupList({})
        if(res && !res.length) {
          ElMessage.warning('未收到数据，可能未同步企微数据，请手动同步')
        }
        state.groupList = res
      }
    }
    let timer: any = null
    const onKeyword = () => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        onSearch()
      }, 400)
    }
    onMounted(() => {     
      onTime(1)
    })
    return () => (
      <div class={styles.search}>
        <div class={styles.type_btn}>
          <Radio list={state.btnTypeList} size="small" onChange={onType} />
        </div>
        <div class={styles.time_btn}>
          <Radio list={state.btnTimeList} checked={state.btnTime} onChange={onTime} />
          <div v-show={state.btnTime == 3} class={styles.date_picker}>
            <ElDatePicker
              style="width:200px"
              v-model={state.date}
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              disabled-date={(time: any) => time.getTime() > Date.now()}
              default-time={[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]}
              onChange={onChanegDate}
            />
          </div>
          <div class={styles.input} v-show={state.btnType != 4}>
            <div class={styles.input_name}>任务搜索</div>
            <ElInput vModel={form.TaskKeyword} onInput={onKeyword} placeholder="请输入任务标题搜索" />
          </div>
          <div v-show={state.btnType == 1} class={styles.input}>
            <div class={styles.input_name}>企微群</div>
            <ElSelect
              style="width:300px"
              vModel={form.Groupchats}
              multiple={true}
              clearable
              collapse-tags
              placeholder="请选择"
              onClick={onGroup}
              onChange={onSearch}
              vSlots={{
                default: () => (
                  <>
                    {state.groupList.map((item) => (
                      <ElOption key={item.id} label={item.name} value={item.id} />
                    ))}
                  </>
                )
              }}
            />
          </div>
        </div>
      </div>
    )
  }
})
